﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using DataAnnotationsExtensions.Resources;

namespace DataAnnotationsExtensions
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class NoHtmlAttribute : DataTypeAttribute
    {
        //private static Regex _regex = new Regex(@"^[A-Z0-9]*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        public NoHtmlAttribute()
            : base(DataType.Text)
        {
        }

        public override string FormatErrorMessage(string name)
        {
            if (ErrorMessage == null && ErrorMessageResourceName == null)
            {
                ErrorMessage = ValidatorResources.NoHtmlAttribute_Invalid;
            }

            return base.FormatErrorMessage(name);
        }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }

            string valueAsString = value as string;
            return valueAsString != null && !HasHtmlTag(valueAsString);
        }

        private bool HasHtmlTag(string value)
        { 
            return value.IndexOf('<') >= 0 || value.IndexOf('>') >= 0;
        }
    }
}
